<!-- 授权管理 -->
<style lang="scss">
  .auth {
    display: flex;
    overflow: auto;
    .el-aside {
      .el-aside {
        padding: 20px 0 10px 20px;
      }
    }
    .el-table .cell {
      font-size: 14px;
    }
    .el-card__header {
      background-color: #e5f1fb;
      border-left: 2px solid #2387e2;
    }

    .el-card__body {
      padding: 0;
      overflow: auto;
      height: calc(100vh - 280px);
    }

    .el-tree {
      .is-current > .el-tree-node__content:nth-of-type(1) {
        color: #2387e2;
      }

      .is-current > .el-tree-node__content .el-tree-node__expand-icon {
        color: #2387e2;
      }
    }

    .el-table {
      height: calc(100vh - 245px);
    }
  }
</style>

<template>
  <el-container class="auth">
    <!-- 左边栏 -->
    <el-aside width="60vw">
      <el-container>
        <!-- 单位 -->
        <el-aside width="250px">
          <el-card>
            <div slot="header">
              <span>角色树</span>
            </div>
            <el-tree :data="treeItem"
                     :props="treeProps"
                     ref="tree"
                     node-key="roleId"
                     class="my_tree"
                     :highlight-current="true"
                     :default-expanded-keys="expandedId"
                     :default-checked-keys="expandedId"
                     @node-click="treeClick">
            </el-tree>
          </el-card>
        </el-aside>
        <!-- 用户 -->
        <el-container>
          <!-- 顶栏容器 -->
          <!-- <el-header style="padding-right: 0;">
            <div class="search-box">
              <div class="conditions-box">
                <div class="conditions-item">
                  <el-input v-model="searchItem.userName"
                            size="small"
                            placeholder="请输入用户姓名"
                            @change="doSearch"
                            style="width: 160px;"></el-input>
                </div>
              </div>
              <div class="search-btn">
                <el-button type="primary"
                           size="small"
                           @click="doSearch">搜索</el-button>
              </div>
            </div>
          </el-header> -->
          <el-main style="padding-right: 0;">
            <el-row type="flex"
                    justify="end">
              <el-button @click="handleAddUser"
                         size="mini"
                         type="primary">添加用户</el-button>
            </el-row>
            <el-table :data="tableItem"
                      stripe
                      :height="tableHeight"
                      v-loading="tableLoading"
                      @row-click="selectRowUser">
              <!-- <el-table-column align="center"
                               label="">
                <template slot-scope="{row}">
                  <el-radio :label="row.userId"
                            v-model="currentUserId">&nbsp;</el-radio>
                </template>
              </el-table-column> -->
              <el-table-column prop="bmjc"
                               label="单位名称"
                               align="center"></el-table-column>
              <el-table-column prop="name"
                               label="用户姓名"
                               align="center"></el-table-column>
              <el-table-column label="操作"
                               align="center">
                <template #default="{row}">
                  <el-button @click="handleTableDelete(row)"
                             type="text"
                             style="color: #F56C6C; padding: 0; font-size:14px">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination style="float: right;"
                           :small="true"
                           :current-page="tableItem.current"
                           :page-count="tableItem.pages"
                           :total="tableItem.total"
                           :page-sizes="[10, 20, 50, 100]"
                           layout="total"></el-pagination>
          </el-main>
        </el-container>
      </el-container>
    </el-aside>
    <el-main>
      <!-- <el-main style="padding: 20px 20px 10px 20px;">
        <el-card class="box-card">
          <div slot="header">
            <span></span>
          </div>
          <el-tree ref="menuTree"
                   :data="menuTreeItem"
                   :props="menuTreeProps"
                   node-key="menuId"
                   :highlight-current="true"
                   :default-expanded-keys="menuExpandedId"
                   show-checkbox
                   :default-expand-all="true"
                   :default-checked-keys="checkedKeys"
                   @check-change="menuTreeClick"
                   v-loading="authLoading"></el-tree>
        </el-card>
      </el-main> -->
      <el-row type="flex"
              justify="end">
        <el-button @click="handleAddMenu"
                   size="mini"
                   type="primary">确认添加</el-button>
      </el-row>
      <el-table :data="menuTableData.data"
                stripe
                :height="tableHeight"
                v-loading="menutableLoading"
                ref="menuTable"
                @cell-dblclick="handleCellClickMenu"
                @selection-change="handleSelectionChange">
        <!-- <el-table-column align="center"
                               label="">
                <template slot-scope="{row}">
                  <el-radio :label="row.userId"
                            v-model="currentUserId">&nbsp;</el-radio>
                </template>
              </el-table-column> -->
        <el-table-column type="selection"
                         align="center"
                         width="55">
        </el-table-column>
        <el-table-column prop="name"
                         label="菜单名称"
                         align="center"></el-table-column>
        <!-- <el-table-column prop="deptName"
                               label="单位名称"
                               align="center"></el-table-column> -->
      </el-table>
      <el-pagination style="float: right;"
                     :small="true"
                     :current-page="tableItem.current"
                     :page-count="tableItem.pages"
                     :total="menuTableData.total"
                     :page-sizes="[10, 20, 50, 100]"
                     layout="total"></el-pagination>

    </el-main>
    <addUserDialog v-if="visibleConfig.addUserDialogVisible"
                   :visible.sync="visibleConfig.addUserDialogVisible" />
    <addMenuDialog v-if="visibleConfig.addMenuDialogVisible"
                   :visible.sync="visibleConfig.addMenuDialogVisible" />
  </el-container>
</template>

<script>
  import addUserDialog from './compontents/dialog-addUser.vue'
  import addMenuDialog from './compontents/dialog-addMenu.vue'
  export default {
    components: { addUserDialog, addMenuDialog },
    data () {
      return {
        // 单位树
        treeItem: [],
        treeProps: {
          children: 'childs',
          label: 'name'
        },
        expandedId: [],
        // 菜单树
        menuTreeItem: [],
        menuTreeProps: {
          children: 'childs',
          label: 'roleName'
        },
        menuExpandedId: [],
        // 查询
        searchItem: {
        },
        // 表格
        tableHeight: -1,
        tableItem: {},
        tableLoading: false,
        menutableLoading: false,
        // 用户table单选
        currentUserId: '',
        checkedKeys: [],
        authLoading: false,
        checkFlag: true,
        menuTableData: {
          data: []
        },
        visibleConfig: {
          addUserDialogVisible: false, // 添加用户
          addMenuDialogVisible: false // 添加菜单
        },
        meunList: []
      }
    },
    methods: {
      // 获取单位树
      getDeptTree () {
        this.$axios.get(this.$api.auth.getTreeList).then((rs) => {
          if (rs) {
            this.treeItem = rs
            if (rs[0]) {
              this.searchItem.roleId = rs[0].jsid
              this.expandedId[0] = rs[0].jsid
              this.searchItem.title = rs[0].name
              this.$nextTick(() => {
                let tree = document.querySelectorAll('.my_tree .el-tree-node__content')[0]
                tree.click()
              })
            }
          }
        })
      },
      // table - 操作  -- 删除
      handleTableDelete (row) {
        this.$confirm('此操作将删除该用户, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.get(this.$api.auth.removeUserRole + `/${row.userId}`).then(res => {
            if (res) {
              this.$message.success('操作成功!')
              this.doSearch()
            }
          })
        }).catch(() => false)
      },
      handleSelectionChange (selection, row) {
        this.searchItem.menuIds = selection.map(item => item.menuId)
      },
      // 树节点点击事件
      treeClick (data) {
        this.searchItem.userName = ''
        this.searchItem.roleId = data.jsid
        this.searchItem.title = data.name
        this.doSearch()
      },
      // 查询
      async doSearch () {
        await this.getUserList()
        await this.getMenuList()
      },
      // 获取菜单列表
      getMenuList () {
        // this.$axios.post(this.$api.auth.getPage, {
        //   condition: {
        //     roleId: this.searchItem.roleId
        //   }
        // }).then(res => {
        //   console.log(res);
        //   // if (res) {
        //   //   this.menuTableData.data = res.records
        //   //   this.getRoleMenu()
        //   // }
        // })
      },
      // 获取角色下的菜单
      getRoleMenu () {
        this.$axios.get(this.$api.auth.getAuthMenusByRoleId + '/' + this.searchItem.roleId).then(res => {
          if (res) {
            this.meunList = res
            if (this.menuTableData.data.length > 0) {
              let paths = res.map(item => item.path) || []
              if (paths.length <= 0) return
              this.menuTableData.data.forEach((item, index) => {
                if (paths.includes(item.path)) {
                  this.$nextTick(() => this.$refs.menuTable.toggleRowSelection(this.$refs.menuTable.data[index], true))
                }
              })
            }
          }
        })
      },
      // 获取用户列表
      getUserList () {
        this.tableLoading = true
        var data = {
          condition: {
            roleId: this.searchItem.roleId
          }
        }
        this.$axios.post(this.$api.auth.getPage, data).then((rs) => {
          if (rs) {
            this.tableItem = rs
            // if (this.tableItem.size !== this.tableItem.total) {
            //   this.tableItem.size = this.tableItem.total
            //   this.getUserList()
            // }
            this.tableLoading = false
          }
        })
      },
      // 选中用户行
      selectRowUser (row, event, column) {
        this.currentUserId = row.userId
        // this.getMenuTree()
      },
      // 获取菜单树
      getMenuTree () {
        // this.$axios.get(this.$api.auth.getMenuTree).then((rs) => {
        //   if (rs) {
        //     console.log(rs, 6333);
        //     // this.menuTreeItem = rs
        //     // this.getAuthMenu()
        //   }
        // })
      },
      // 获取已经授权菜单
      getAuthMenu () {
        this.checkFlag = false
        this.checkedKeys = []
        this.$axios.get(this.$api.auth.getAuth + '/' + this.currentUserId).then((rs) => {
          if (rs) {
            // this.$refs.menuTree.setCheckedKeys(rs);
            this.checkedKeys = rs
          }
        })
      },
      // 树节点点击事件
      menuTreeClick (data, isCheck) {
        if (this.checkFlag) {
          this.authLoading = true
          this.$axios.post(this.$api.auth.doAuth, {
            menuId: data.menuId,
            userId: this.currentUserId,
            type: isCheck
          }).then((rs) => {
            if (rs) {
              this.$message({
                message: '操作成功!',
                showClose: true,
                type: 'success',
                closeOnClickModal: false
              })
              this.doSearch()
              this.authLoading = false
            }
          })
        }
      },
      // 添加用户按钮
      handleAddUser () {
        let { roleId, title } = this.searchItem
        this.$router.replace(this.$route.path + `?roleId=${roleId}&title=${title}`)
        this.visibleConfig.addUserDialogVisible = true
      },
      // 双击菜单单元格
      handleCellClickMenu (row, column, cell, event) {
        this.menuTableData.data.forEach((item, index) => {
          if (item.menuId === row.menuId) {
            this.$nextTick(() => this.$refs.menuTable.toggleRowSelection(this.$refs.menuTable.data[index], true))
          }
        })
      },
      // 添加菜单按钮
      handleAddMenu () {
        // this.$router.replace(this.$route.path + `?roleId=${this.searchItem.roleId}`)
        // this.visibleConfig.addMenuDialogVisible = true
        this.menutableLoading = true
        this.$axios.post(this.$api.auth.doAuth, this.searchItem).then(res => {
          this.menutableLoading = false
          if (res) {
            this.$message.success('操作成功!')
          }
        })
      }
    },
    watch: {
      menuTreeItem: function () {
        this.checkFlag = true
      }
    },
    mounted: function () {
      this.getDeptTree()
    }
  }
</script>
